<template>
  <div class="balance-container">
    <div class="page-header-wrapper">
      <el-button @click="goHome" circle size="large" class="back-btn">
        <el-icon><ArrowLeft /></el-icon>
      </el-button>
    </div>
    <div class="balance-header">
      <h1>💰 微信余额管理</h1>
      <p class="subtitle">透明管理，共同成长</p>
    </div>

    <!-- 余额信息卡片 -->
    <div class="balance-cards">
      <!-- 我的余额 -->
      <div class="balance-card my-balance">
        <div class="card-header">
          <span class="label">💝 我的余额</span>
          <el-tag v-if="balanceInfo.myBalanceStatus === 0" type="warning" size="small">待确认</el-tag>
          <el-tag v-else type="success" size="small">已确认</el-tag>
        </div>
        <div class="amount">¥{{ formatAmount(balanceInfo.myBalance) }}</div>
        <div class="actions">
          <el-button 
            v-if="balanceInfo.myBalanceStatus === null" 
            type="primary" 
            size="small" 
            @click="showSetBalanceDialog = true"
            round>
            设置余额
          </el-button>
          <el-button 
            v-else 
            type="primary" 
            size="small" 
            @click="showUpdateBalanceDialog = true"
            round>
            修改余额
          </el-button>
        </div>
      </div>

      <!-- 对方余额 -->
      <div class="balance-card partner-balance">
        <div class="card-header">
          <span class="label">💖 {{ balanceInfo.partner?.nickname || '对方' }}的余额</span>
          <el-tag v-if="balanceInfo.partnerBalanceStatus === 0" type="warning" size="small">待确认</el-tag>
          <el-tag v-else-if="balanceInfo.partnerBalanceStatus === 1" type="success" size="small">已确认</el-tag>
        </div>
        <div class="amount">¥{{ formatAmount(balanceInfo.partnerBalance) }}</div>
        <div class="actions">
          <el-button
            v-if="balanceInfo.partnerBalanceStatus === 0"
            type="success"
            size="small"
            @click="confirmPartnerBalanceAction"
            round>
            确认余额
          </el-button>
        </div>
      </div>
    </div>

    <!-- 待审批的余额修改请求 -->
    <div v-if="pendingRequests.length > 0" class="pending-section">
      <h2>📋 待我审批</h2>
      <div class="request-list">
        <div v-for="request in pendingRequests" :key="request.id" class="request-card">
          <div class="request-info">
            <div class="request-amount">
              <span class="label">新余额：</span>
              <span class="value">¥{{ formatAmount(request.newBalance) }}</span>
            </div>
            <div class="request-time">{{ formatDateTime(request.createdAt) }}</div>
          </div>
          <div class="request-actions">
            <el-button type="success" size="small" @click="approveRequest(request.id, true)" round>同意</el-button>
            <el-button type="danger" size="small" @click="showRejectDialog(request.id)" round>拒绝</el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 我发起的余额修改请求 -->
    <div v-if="myRequests.length > 0" class="my-requests-section">
      <h2>📝 我的申请</h2>
      <div class="request-list">
        <div v-for="request in myRequests" :key="request.id" class="request-card">
          <div class="request-info">
            <div class="request-amount">
              <span class="label">新余额：</span>
              <span class="value">¥{{ formatAmount(request.newBalance) }}</span>
            </div>
            <div class="request-time">{{ formatDateTime(request.createdAt) }}</div>
          </div>
          <div class="request-status">
            <el-tag v-if="request.status === 0" type="warning">待审批</el-tag>
            <el-tag v-else-if="request.status === 1" type="success">已同意</el-tag>
            <el-tag v-else type="danger">已拒绝</el-tag>
          </div>
          <div v-if="request.status === 2 && request.rejectReason" class="reject-reason">
            拒绝理由：{{ request.rejectReason }}
          </div>
        </div>
      </div>
    </div>

    <!-- 余额变更历史记录 -->
    <div class="change-log-section">
      <div class="section-header">
        <h2>📊 余额变更历史</h2>
        <el-select v-model="changeTypeFilter" placeholder="全部类型" size="small" @change="loadChangeLogs" style="width: 150px;">
          <el-option label="全部类型" value="" />
          <el-option label="账单支出" value="bill_expense" />
          <el-option label="手动调整" value="manual_adjust" />
          <el-option label="金库存入" value="treasury_deposit" />
          <el-option label="金库取出" value="treasury_withdraw" />
        </el-select>
      </div>

      <div v-loading="changeLogLoading" class="change-log-list">
        <div v-if="changeLogs.length === 0" class="empty-state">
          <el-empty description="暂无变更记录" />
        </div>

        <div v-else class="log-items">
          <div v-for="log in changeLogs" :key="log.id" :class="['log-item', log.amount < 0 ? 'expense' : 'income']">
            <div class="log-icon">
              {{ getChangeTypeIcon(log.changeType) }}
            </div>
            <div class="log-info">
              <div class="log-description">{{ log.description }}</div>
              <div class="log-meta">
                <span class="log-type">{{ getChangeTypeLabel(log.changeType) }}</span>
                <span class="log-time">{{ formatDateTime(log.createdAt) }}</span>
              </div>
              <div class="log-balance-change">
                <span class="before">¥{{ formatAmount(log.balanceBefore) }}</span>
                <span class="arrow">→</span>
                <span class="after">¥{{ formatAmount(log.balanceAfter) }}</span>
              </div>
            </div>
            <div :class="['log-amount', log.amount < 0 ? 'negative' : 'positive']">
              {{ log.amount < 0 ? '' : '+' }}¥{{ formatAmount(Math.abs(log.amount)) }}
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div v-if="changeLogTotal > 0" class="pagination-wrapper">
          <el-pagination
            v-model:current-page="changeLogPage"
            v-model:page-size="changeLogPageSize"
            :total="changeLogTotal"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next"
            @current-change="loadChangeLogs"
            @size-change="loadChangeLogs" />
        </div>
      </div>
    </div>

    <!-- 设置初始余额对话框 -->
    <el-dialog v-model="showSetBalanceDialog" title="💰 设置初始余额" width="90%" :close-on-click-modal="false">
      <el-form :model="setBalanceForm" :rules="balanceRules" ref="setBalanceFormRef" label-width="100px">
        <el-form-item label="微信余额" prop="balance">
          <el-input 
            v-model="setBalanceForm.balance" 
            placeholder="请输入微信余额" 
            type="number"
            step="0.01">
            <template #prefix>¥</template>
          </el-input>
        </el-form-item>
        <el-alert 
          title="提示：设置后需要对方确认才能生效" 
          type="info" 
          :closable="false" 
          show-icon />
      </el-form>
      <template #footer>
        <el-button @click="showSetBalanceDialog = false">取消</el-button>
        <el-button type="primary" @click="submitSetBalance" :loading="loading">确定</el-button>
      </template>
    </el-dialog>

    <!-- 修改余额对话框 -->
    <el-dialog v-model="showUpdateBalanceDialog" title="✏️ 修改余额" width="90%" :close-on-click-modal="false">
      <el-form :model="updateBalanceForm" :rules="updateBalanceRules" ref="updateBalanceFormRef" label-width="100px">
        <el-form-item label="新余额" prop="newBalance">
          <el-input 
            v-model="updateBalanceForm.newBalance" 
            placeholder="请输入新余额" 
            type="number"
            step="0.01">
            <template #prefix>¥</template>
          </el-input>
        </el-form-item>
        <el-form-item label="修改原因" prop="reason">
          <el-input 
            v-model="updateBalanceForm.reason" 
            type="textarea" 
            :rows="3"
            placeholder="请说明修改原因，如：发工资了、消费支出等" />
        </el-form-item>
        <el-alert 
          title="提示：修改后需要对方审批才能生效" 
          type="warning" 
          :closable="false" 
          show-icon />
      </el-form>
      <template #footer>
        <el-button @click="showUpdateBalanceDialog = false">取消</el-button>
        <el-button type="primary" @click="submitUpdateBalance" :loading="loading">提交申请</el-button>
      </template>
    </el-dialog>

    <!-- 拒绝理由对话框 -->
    <el-dialog v-model="showRejectReasonDialog" title="❌ 拒绝理由" width="90%" :close-on-click-modal="false">
      <el-form :model="rejectForm" :rules="rejectRules" ref="rejectFormRef" label-width="100px">
        <el-form-item label="拒绝理由" prop="rejectReason">
          <el-input 
            v-model="rejectForm.rejectReason" 
            type="textarea" 
            :rows="4"
            placeholder="请填写拒绝理由" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showRejectReasonDialog = false">取消</el-button>
        <el-button type="danger" @click="submitReject" :loading="loading">确定拒绝</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import {
  getBalanceInfo,
  setBalance,
  confirmPartnerBalance,
  createBalanceRequest,
  approveBalanceRequest,
  getPendingBalanceRequests,
  getMyBalanceRequests,
  getBalanceChangeLogList
} from '@/api'

const router = useRouter()

// 响应式数据
const balanceInfo = ref({
  myBalance: 0,
  myBalanceStatus: null,
  partnerBalance: 0,
  partnerBalanceStatus: null,
  partner: null
})

// 余额变更历史
const changeLogs = ref([])
const changeLogLoading = ref(false)
const changeLogPage = ref(1)
const changeLogPageSize = ref(10)
const changeLogTotal = ref(0)
const changeTypeFilter = ref('')

const pendingRequests = ref([])
const myRequests = ref([])
const loading = ref(false)

// 对话框显示状态
const showSetBalanceDialog = ref(false)
const showUpdateBalanceDialog = ref(false)
const showRejectReasonDialog = ref(false)

// 表单数据
const setBalanceForm = ref({ balance: '' })
const updateBalanceForm = ref({ newBalance: '', reason: '' })
const rejectForm = ref({ rejectReason: '', requestId: null })

// 表单引用
const setBalanceFormRef = ref(null)
const updateBalanceFormRef = ref(null)
const rejectFormRef = ref(null)

// 表单验证规则
const balanceRules = {
  balance: [
    { required: true, message: '请输入余额', trigger: 'blur' },
    { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的金额格式', trigger: 'blur' }
  ]
}

const updateBalanceRules = {
  newBalance: [
    { required: true, message: '请输入新余额', trigger: 'blur' },
    { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的金额格式', trigger: 'blur' }
  ],
  reason: [
    { required: true, message: '请填写修改原因', trigger: 'blur' },
    { min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' }
  ]
}

const rejectRules = {
  rejectReason: [
    { required: true, message: '请填写拒绝理由', trigger: 'blur' },
    { min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' }
  ]
}

// 格式化金额
const formatAmount = (amount) => {
  if (amount === null || amount === undefined) return '0.00'
  return Number(amount).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', { 
    year: 'numeric', 
    month: '2-digit', 
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 加载余额信息
const loadBalanceInfo = async () => {
  try {
    const res = await getBalanceInfo()
    if (res.code === 200) {
      balanceInfo.value = res.data
    }
  } catch (error) {
    console.error('加载余额信息失败', error)
  }
}

// 加载待审批请求
const loadPendingRequests = async () => {
  try {
    const res = await getPendingBalanceRequests()
    if (res.code === 200) {
      pendingRequests.value = res.data
    }
  } catch (error) {
    console.error('加载待审批请求失败', error)
  }
}

// 加载我的请求
const loadMyRequests = async () => {
  try {
    const res = await getMyBalanceRequests()
    if (res.code === 200) {
      myRequests.value = res.data
    }
  } catch (error) {
    console.error('加载我的请求失败', error)
  }
}

// 设置初始余额
const submitSetBalance = async () => {
  await setBalanceFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const res = await setBalance({ balance: Number(setBalanceForm.value.balance) })
        if (res.code === 200) {
          ElMessage.success('余额设置成功，等待对方确认')
          showSetBalanceDialog.value = false
          setBalanceForm.value.balance = ''
          await loadBalanceInfo()
        }
      } catch (error) {
        ElMessage.error(error.response?.data?.msg || '设置失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 确认对方余额
const confirmPartnerBalanceAction = async () => {
  try {
    await ElMessageBox.confirm('确认对方的余额设置吗？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'info'
    })

    loading.value = true
    const res = await confirmPartnerBalance(balanceInfo.value.partner.id)
    if (res.code === 200) {
      ElMessage.success('确认成功')
      await loadBalanceInfo()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.msg || '确认失败')
    }
  } finally {
    loading.value = false
  }
}

// 提交余额修改请求
const submitUpdateBalance = async () => {
  await updateBalanceFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const res = await createBalanceRequest({
          newBalance: Number(updateBalanceForm.value.newBalance),
          reason: updateBalanceForm.value.reason
        })
        if (res.code === 200) {
          ElMessage.success('申请已提交，等待对方审批')
          showUpdateBalanceDialog.value = false
          updateBalanceForm.value = { newBalance: '', reason: '' }
          await loadMyRequests()
        }
      } catch (error) {
        ElMessage.error(error.response?.data?.msg || '提交失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 加载余额变更历史
const loadChangeLogs = async () => {
  changeLogLoading.value = true
  try {
    const res = await getBalanceChangeLogList({
      pageNum: changeLogPage.value,
      pageSize: changeLogPageSize.value,
      changeType: changeTypeFilter.value || undefined
    })
    if (res.code === 200) {
      changeLogs.value = res.data.records
      changeLogTotal.value = res.data.total
    }
  } catch (error) {
    console.error('加载余额变更历史失败', error)
  } finally {
    changeLogLoading.value = false
  }
}

// 获取变更类型图标
const getChangeTypeIcon = (type) => {
  const iconMap = {
    bill_expense: '💸',
    manual_adjust: '✏️',
    treasury_deposit: '🏦',
    treasury_withdraw: '💰'
  }
  return iconMap[type] || '📝'
}

// 获取变更类型标签
const getChangeTypeLabel = (type) => {
  const labelMap = {
    bill_expense: '账单支出',
    manual_adjust: '手动调整',
    treasury_deposit: '金库存入',
    treasury_withdraw: '金库取出'
  }
  return labelMap[type] || '其他'
}

// 显示拒绝对话框
const showRejectDialog = (requestId) => {
  rejectForm.value.requestId = requestId
  rejectForm.value.rejectReason = ''
  showRejectReasonDialog.value = true
}

// 审批请求
const approveRequest = async (requestId, approved) => {
  try {
    await ElMessageBox.confirm(`确定${approved ? '同意' : '拒绝'}此申请吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: approved ? 'success' : 'warning'
    })

    loading.value = true
    const res = await approveBalanceRequest({
      requestId,
      approved,
      rejectReason: null
    })
    if (res.code === 200) {
      ElMessage.success(approved ? '已同意' : '已拒绝')
      await loadPendingRequests()
      await loadBalanceInfo()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.msg || '操作失败')
    }
  } finally {
    loading.value = false
  }
}

// 提交拒绝
const submitReject = async () => {
  await rejectFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const res = await approveBalanceRequest({
          requestId: rejectForm.value.requestId,
          approved: false,
          rejectReason: rejectForm.value.rejectReason
        })
        if (res.code === 200) {
          ElMessage.success('已拒绝')
          showRejectReasonDialog.value = false
          await loadPendingRequests()
        }
      } catch (error) {
        ElMessage.error(error.response?.data?.msg || '操作失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 返回主页
const goHome = () => {
  router.push('/home')
}

// 页面加载时获取数据
onMounted(() => {
  loadBalanceInfo()
  loadPendingRequests()
  loadMyRequests()
  loadChangeLogs()
})
</script>

<style scoped>
.balance-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #ffeef8 0%, #fff5f7 100%);
  padding: 20px;
}

.page-header-wrapper {
  margin-bottom: 10px;
}

.back-btn {
  background: white;
  border: none;
  box-shadow: 0 2px 12px rgba(255, 154, 158, 0.2);
}

.balance-header {
  text-align: center;
  margin-bottom: 30px;
}

.balance-header h1 {
  font-size: 28px;
  font-weight: bold;
  background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  margin-bottom: 8px;
}

.subtitle {
  color: #999;
  font-size: 14px;
}

.balance-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.balance-card {
  background: white;
  border-radius: 24px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(255, 154, 158, 0.15);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.balance-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 30px rgba(255, 154, 158, 0.25);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.card-header .label {
  font-size: 16px;
  font-weight: 500;
  color: #666;
}

.amount {
  font-size: 36px;
  font-weight: bold;
  background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  margin-bottom: 16px;
}

.actions {
  display: flex;
  gap: 10px;
}

.pending-section,
.my-requests-section {
  background: white;
  border-radius: 24px;
  padding: 24px;
  margin-bottom: 20px;
  box-shadow: 0 4px 20px rgba(255, 154, 158, 0.15);
}

.pending-section h2,
.my-requests-section h2 {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
}

.request-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.request-card {
  background: linear-gradient(135deg, #fff5f7 0%, #ffeef8 100%);
  border-radius: 16px;
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.request-info {
  flex: 1;
  min-width: 200px;
}

.request-amount {
  font-size: 16px;
  margin-bottom: 8px;
}

.request-amount .label {
  color: #666;
}

.request-amount .value {
  font-weight: bold;
  color: #ff9a9e;
  font-size: 18px;
}

.request-time {
  font-size: 12px;
  color: #999;
}

.request-actions {
  display: flex;
  gap: 10px;
}

.request-status {
  min-width: 80px;
  text-align: right;
}

.reject-reason {
  width: 100%;
  margin-top: 10px;
  padding: 10px;
  background: #fff;
  border-radius: 8px;
  font-size: 14px;
  color: #666;
}

/* 余额变更历史样式 */
.change-log-section {
  margin-top: 30px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h2 {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.change-log-list {
  background: white;
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(255, 154, 158, 0.1);
}

.log-items {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.log-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px;
  background: #fafafa;
  border-radius: 12px;
  transition: all 0.3s ease;
}

.log-item:hover {
  background: #f5f5f5;
  transform: translateX(5px);
}

.log-item.expense {
  border-left: 3px solid #ff6b6b;
}

.log-item.income {
  border-left: 3px solid #51cf66;
}

.log-icon {
  font-size: 28px;
  flex-shrink: 0;
}

.log-info {
  flex: 1;
  min-width: 0;
}

.log-description {
  font-size: 15px;
  font-weight: 500;
  color: #333;
  margin-bottom: 5px;
}

.log-meta {
  display: flex;
  gap: 15px;
  font-size: 13px;
  color: #999;
  margin-bottom: 5px;
}

.log-balance-change {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  color: #666;
}

.log-balance-change .before {
  color: #999;
}

.log-balance-change .arrow {
  color: #ff9a9e;
}

.log-balance-change .after {
  color: #333;
  font-weight: 500;
}

.log-amount {
  font-size: 18px;
  font-weight: bold;
  flex-shrink: 0;
}

.log-amount.negative {
  color: #ff6b6b;
}

.log-amount.positive {
  color: #51cf66;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .balance-container {
    padding: 15px;
  }

  .balance-header h1 {
    font-size: 24px;
  }

  .balance-cards {
    grid-template-columns: 1fr;
  }

  .amount {
    font-size: 28px;
  }

  .request-card {
    flex-direction: column;
    align-items: flex-start;
  }

  .request-actions {
    width: 100%;
    justify-content: flex-end;
  }

  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .log-item {
    flex-direction: column;
    align-items: flex-start;
  }

  .log-amount {
    align-self: flex-end;
  }

  .log-balance-change {
    flex-wrap: wrap;
  }
}
</style>


